<template>
  <div class="app-container">
    <div class="filter-container" style="text-align: center;">
      <el-input v-model="searchname" placeholder="elasticSearch根据用户名或QQ或手机号搜索" style="width: 400px;margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" type="success" icon="el-icon-search" @click="handleEs">
        搜索
      </el-button>
      <el-button  v-if="checkPermission([1])"  v-waves :loading="downloadLoading" class="filter-item" type="warning" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >

      <el-table-column align="center" label="序号" width="95">
              <template slot-scope="row">
                {{ row.$index+1 }}
              </template>
            </el-table-column>
      <el-table-column label="用户名" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone}}</span>
        </template>
      </el-table-column>
      <el-table-column label="QQ号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.qqEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button  v-if="checkPermission([1])" type="warning"  icon="el-icon-unlock"  size="mini" @click="handleCreate(row)">
            授权
          </el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="checkPermission([1])"  icon="el-icon-delete"  size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" placeholder="输入用户名" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="姓名" prop="password">
          <el-input v-model="temp.name" placeholder="输入姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="输入手机号" />
        </el-form-item>
        <el-form-item label="QQ号" prop="qqEmail">
          <el-input v-model="temp.qqEmail" placeholder="输入QQ号"/>
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="授权密码" prop="password">
          <el-input v-model="temp.password2" placeholder="初始化管理员密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList,es, getExport,getUpdate,getCreate} from '@/api/user2'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import fileDownload from 'js-file-download'
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      password2:null,
      searchname:null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        searchName:null
      },
      showReviewer: false,
      temp: {
       password2:null,
       name:null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '授权'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
     checkPermission,
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    handleCreate(row) {
     this.temp = Object.assign({}, row) // copy obj
     this.dialogStatus = 'create'
     this.dialogFormVisible = true
     this.$nextTick(() => {
       this.$refs['dataForm'].clearValidate()
     })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          getCreate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '授予用户管理员身份成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
         getUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '更新用户信息成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleEs(){
      if(this.searchname==null||this.searchname==''){
         this.getList();
      }else{

        es(this.searchname).then(res=>{
          this.total=res.data.total,
          this.list=res.data.items
        })
      }

    },

    handleDownload() {
       getExport().them(res=>{

       })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
